import openai
import json

openai.api_base = "http://localhost:8000/v1"
openai.api_key = "none"

tools = [
    {
        "name": "run_code",
        "description": "编写一个代码所使用的函数",
        "parameters": {
            "type": "object",
            "properties": {
                "filename": {
                    "description": "需要编写的代码文件名称"
                },
                "filecontent": {
                    "description": "需要编写的具体代码"
                },
            },
            "required": ['filecontent']
        }
    },
    
]


query = "编写一个使用flask的登录页面的python文件"
params = dict(model="chatglm3", messages=[{"role": "user", "content": query}],functions=tools)
    
response = openai.ChatCompletion.create(**params)
print(response.choices[0].message.function_call.name)
print(response.choices[0].message.function_call.arguments)
function_args = json.loads(response.choices[0].message.function_call.arguments)
filename = str(function_args["filename"])
filecontent = str(function_args["filecontent"])

def run_code(filename,filecontent):
    f = open(filename, "w")
    f.write(filecontent)
    f.close()

run_code(filename=filename,filecontent=filecontent)

